//
//  ViewController.m
//  imageSet
//
//  Created by sunkai on 2017/7/13.
//  Copyright © 2017年 sunkai. All rights reserved.
//

#import "ViewController.h"
#import "LLNetWork.h"
#import "ListViewController.h"
#import <LocalAuthentication/LocalAuthentication.h>

@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (nonatomic,strong)UICollectionView *mCollection;
@property (nonatomic,strong)NSArray *dataArray;

@property (nonatomic,copy)NSString *huancunStr;
@property (nonatomic,strong)UIButton *rightButton;
@property (nonatomic,assign)BOOL isLoadData;
@end

@implementation ViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    _isLoadData = NO;
    NSUInteger intg = [[SDImageCache sharedImageCache] getSize];
    _huancunStr = [NSString stringWithFormat:@"%.2fMB",intg/1024.0/1024.0];
    if (_rightButton) {
        [_rightButton setTitle:_huancunStr forState:UIControlStateNormal];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"首页";
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    NSString * jsonPath = [[NSBundle mainBundle]pathForResource:@"club-tags" ofType:@"json"];
    NSData * jsonData = [[NSData alloc]initWithContentsOfFile:jsonPath];
    NSMutableDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
    
    _dataArray = [NSArray array];
    _dataArray = jsonDic[@"list"];
    [self createTouchID];
    [self addRightButton];
}
- (void)addRightButton {
    _rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 44)];
    [_rightButton setTitle:_huancunStr forState:UIControlStateNormal];
    [_rightButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_rightButton addTarget:self action:@selector(rightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_rightButton];
}
- (void)rightBtnClick:(UIButton *)button {
    [[SDImageCache sharedImageCache] clearDisk];
    [button setTitle:@"0.00MB" forState:UIControlStateNormal];
}
#pragma mark collectionview
- (void)createCollectionView {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    _mCollection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64) collectionViewLayout:flowLayout];
    _mCollection.backgroundColor = [UIColor whiteColor];
    _mCollection.delegate = self;
    _mCollection.dataSource = self;
    [_mCollection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCellID"];
    [_mCollection registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerID"];
    [self.view addSubview:_mCollection];
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return _dataArray.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [_dataArray[section][@"list"] count];
}
#pragma mark 区头
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerID" forIndexPath:indexPath];
    headerView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
    UILabel *headerLabel = [headerView viewWithTag:111];
    if (!headerLabel) {
        headerLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 5, SCREEN_WIDTH, 20)];
        headerLabel.tag = 111;
        [headerView addSubview:headerLabel];
    }
    headerLabel.text = _dataArray[indexPath.section][@"title"];
    return headerView;
}
//区头的高
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(SCREEN_WIDTH, 30);
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UICollectionViewCellID" forIndexPath:indexPath];
    UILabel *label = [cell.contentView viewWithTag:222];
    CGFloat cellWidth = (SCREEN_WIDTH-30)/3;
    if (!label) {
        label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, cellWidth, 30)];
        label.tag = 222;
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:14];
        label.layer.borderWidth = 1;
        label.layer.borderColor = [UIColor grayColor].CGColor;
        label.layer.cornerRadius = 10;
        label.layer.masksToBounds = YES;
        [cell.contentView addSubview:label];
    }
    label.text = _dataArray[indexPath.section][@"list"][indexPath.row][@"title"];
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_isLoadData) {
        return;
    }
    _isLoadData = YES;
    NSString *urlStr = [NSString stringWithFormat:@"http://api.kongyouran.com/tag/?page=1&id=%@",_dataArray[indexPath.section][@"list"][indexPath.row][@"id"]];
    [LLNetWork getDataWithURLString:urlStr callBack:^(id responseObject, NSError *error) {
        NSLog(@"%@",responseObject);
        ListViewController *listVC = [[ListViewController alloc]init];
        listVC.listArray = responseObject[@"list"];
        listVC.titleStr = _dataArray[indexPath.section][@"list"][indexPath.row][@"title"];
        [self.navigationController pushViewController:listVC animated:YES];
        
    }];
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat cellWidth = (SCREEN_WIDTH-30)/3;
    return CGSizeMake(cellWidth, 30);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 5, 10, 5);
}

- (void)createTouchID {
    //创建LAContext
    LAContext *context = [LAContext new]; //这个属性是设置指纹输入失败之后的弹出框的选项
    context.localizedFallbackTitle = @"没有忘记密码";
    NSError *error = nil;
    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
                             error:&error]) {
        NSLog(@"支持指纹识别");
        [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
                localizedReason:@"指纹解锁" reply:^(BOOL success, NSError * _Nullable error) {
                    if (success) {
                        NSLog(@"验证成功 刷新主界面");
                        LLDispatch_main(^{
                            [self createCollectionView];
                        });
                    }else{
                        NSLog(@"%@",error.localizedDescription);
                        switch (error.code) {
                            case LAErrorSystemCancel:
                            {
                                NSLog(@"系统取消授权，如其他APP切入");
                                break;
                            }
                            case LAErrorUserCancel:
                            {
                                NSLog(@"用户取消验证Touch ID");
                                break;
                            }
                            case LAErrorAuthenticationFailed:
                            {
                                NSLog(@"授权失败");
                                break;
                            }
                            case LAErrorPasscodeNotSet:
                            {
                                NSLog(@"系统未设置密码");
                                break;
                            }
                            case LAErrorTouchIDNotAvailable:
                            {
                                NSLog(@"设备Touch ID不可用，例如未打开");
                                break;
                            }
                            case LAErrorTouchIDNotEnrolled:
                            {
                                NSLog(@"设备Touch ID不可用，用户未录入");
                                break;
                            }
                            case LAErrorUserFallback:
                            {
                                [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                                    NSLog(@"用户选择输入密码，切换主线程处理");
                                }];
                                break;
                            }
                            default:
                            {
                                [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                                    NSLog(@"其他情况，切换主线程处理");
                                }];
                                break;
                            }
                        }
                    }
                }];
    }else{
        NSLog(@"不支持指纹识别");
        switch (error.code) {
            case LAErrorTouchIDNotEnrolled:
            {
                NSLog(@"TouchID is not enrolled");
                break;
            }
            case LAErrorPasscodeNotSet:
            {
                NSLog(@"A passcode has not been set");
                break;
            }
            default:
            {
                NSLog(@"TouchID not available");
                break;
            }
        }
        
        NSLog(@"%@",error.localizedDescription);
    }
}
@end
